// The MIT License (MIT)

// Copyright (c) 2013 lailongwei<lailongwei@126.com>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of 
// this software and associated documentation files (the "Software"), to deal in 
// the Software without restriction, including without limitation the rights to 
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 
// the Software, and to permit persons to whom the Software is furnished to do so, 
// subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all 
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#include "llbc/common/Export.h"

#include "llbc/core/thread/ILock.h"

#include "llbc/core/thread/Guard.h"

__LLBC_NS_BEGIN

LLBC_LockGuard::LLBC_LockGuard(LLBC_ILock &lock, bool reverse)
: _lock(lock)
, _reverse(reverse)
{
#if LLBC_DEBUG && LLBC_CFG_THREAD_GUARD_DEBUG
    traceline("LLBC_LockGuard: locker[%p] will %s", &lock, (_reverse ? "unlock" : "lock"));
#endif // Guard debug

    if (!_reverse)
        _lock.Lock();
    else
        _lock.Unlock();

#if LLBC_DEBUG && LLBC_CFG_THREAD_GUARD_DEBUG
    traceline("LLBC_LockGuard: locker[%p] %s", &lock, (_reverse ? "unlocked" : "locked"));
#endif // Guard debug
}

LLBC_LockGuard::~LLBC_LockGuard()
{
#if LLBC_DEBUG && LLBC_CFG_THREAD_GUARD_DEBUG
    traceline("LLBC_LockGuard: locker[%p] will %s", &_lock, (_reverse ? "lock" : "unlock"));
#endif // Guard debug

    if (!_reverse)
        _lock.Unlock();
    else
        _lock.Lock();

#if LLBC_DEBUG && LLBC_CFG_THREAD_GUARD_DEBUG
    traceline("LLBC_LockGuard: locker[%p] %s", &_lock, (_reverse ? "locked" : "unlocked"));
#endif // Guard debug
}

__LLBC_NS_END
